//
//  GradientView.swift
//  
//
//  Created by bo wang on 2020/9/4.
//  Copyright © 2020 wangbo. All rights reserved.
//

import UIKit

// 方便添加渐变色的View。不会挡住触摸事件。
class GradientView: HitTestView {
    @IBInspectable var startPoint: CGPoint = CGPoint(x: 0.5, y: 0) {
        didSet {
            updateInternalGradientLayer()
        }
    }

    @IBInspectable var endPoint: CGPoint = CGPoint(x: 0.5, y: 1) {
        didSet {
            updateInternalGradientLayer()
        }
    }

    @IBInspectable var startColor: UIColor? {
        didSet {
            updateInternalGradientLayer()
        }
    }

    @IBInspectable var endColor: UIColor? {
        didSet {
            updateInternalGradientLayer()
        }
    }

    var gradientColors: [UIColor] = [] {
        didSet {
            updateInternalGradientLayer()
        }
    }

    var gradientLocations: [Float] = [] {
        didSet {
            updateInternalGradientLayer()
        }
    }

    lazy var internalGradientLayer: CAGradientLayer = {
        let layer = CAGradientLayer()
        layer.frame.origin = .zero
        layer.isHidden = true
        return layer
    }()

    override init(frame: CGRect) {
        super.init(frame: frame)
        updateInternalGradientLayer()
    }

    required init?(coder: NSCoder) {
        super.init(coder: coder)
        updateInternalGradientLayer()
    }

    override func layoutSubviews() {
        super.layoutSubviews()
        internalGradientLayer.frame = bounds
        layer.insertSublayer(internalGradientLayer, at: 0)
    }

    private func updateInternalGradientLayer() {
        internalGradientLayer.frame = bounds
        layer.insertSublayer(internalGradientLayer, at: 0)
        if !gradientColors.isEmpty {
            internalGradientLayer.colors = gradientColors.map({ $0.cgColor })
            internalGradientLayer.startPoint = startPoint
            internalGradientLayer.endPoint = endPoint
            if !gradientLocations.isEmpty {
                internalGradientLayer.locations = gradientLocations.map({ NSNumber(value: $0) })
            }
            internalGradientLayer.isHidden = false
        } else if let startColor = startColor, let endColor = endColor {
            internalGradientLayer.colors = [startColor.cgColor,
                                            endColor.cgColor]
            internalGradientLayer.startPoint = startPoint
            internalGradientLayer.endPoint = endPoint
            if !gradientLocations.isEmpty {
                internalGradientLayer.locations = gradientLocations.map({ NSNumber(value: $0) })
            }
            internalGradientLayer.isHidden = false
        } else {
            internalGradientLayer.isHidden = true
        }
    }
}
